export interface CookieData {
  name: string;
  value: string;
  domain: string;
  path: string;
  expires?: number;
  httpOnly: boolean;
  secure: boolean;
}

export class CookieManager {
  private cookies: Map<string, CookieData>;
  private tabId: string;

  constructor(tabId: string) {
    this.tabId = tabId;
    this.cookies = new Map();
    this.loadFromStorage();
  }

  // 设置Cookie
  setCookie(cookie: CookieData): void {
    this.cookies.set(cookie.name, cookie);
    this.saveToStorage();
  }

  // 获取Cookie
  getCookie(name: string): CookieData | undefined {
    return this.cookies.get(name);
  }

  // 获取所有Cookie
  getAllCookies(): CookieData[] {
    return Array.from(this.cookies.values());
  }

  // 删除Cookie
  removeCookie(name: string): boolean {
    const existed = this.cookies.delete(name);
    if (existed) {
      this.saveToStorage();
    }
    return existed;
  }

  // 清除所有Cookie
  clearAll(): void {
    this.cookies.clear();
    this.saveToStorage();
  }

  // 导出Cookie为JSON字符串
  exportCookies(): string {
    const cookiesArray = Array.from(this.cookies.entries());
    return JSON.stringify(cookiesArray, null, 2);
  }

  // 从JSON字符串导入Cookie
  importCookies(cookieJson: string): void {
    try {
      const cookiesArray = JSON.parse(cookieJson) as [string, CookieData][];
      this.cookies = new Map(cookiesArray);
      this.saveToStorage();
    } catch (error) {
      console.error('导入Cookie失败:', error);
    }
  }

  // 生成Cookie请求头
  generateCookieHeader(url: string): string {
    const urlObj = new URL(url);
    const domainCookies = Array.from(this.cookies.values()).filter(cookie => 
      this.matchesDomain(cookie.domain, urlObj.hostname) &&
      this.matchesPath(cookie.path, urlObj.pathname) &&
      (!cookie.secure || urlObj.protocol === 'https:') &&
      (!cookie.expires || cookie.expires > Date.now())
    );

    return domainCookies.map(cookie => `${cookie.name}=${cookie.value}`).join('; ');
  }

  // 从Set-Cookie响应头解析并设置Cookie
  parseSetCookieHeader(setCookieHeader: string, url: string): CookieData[] {
    const cookies: CookieData[] = [];
    const urlObj = new URL(url);

    // 简单的Set-Cookie解析（实际项目中应该使用更完整的解析）
    const cookieStrings = setCookieHeader.split(',').map(s => s.trim());

    for (const cookieString of cookieStrings) {
      const parts = cookieString.split(';').map(p => p.trim());
      const [nameValue, ...attributes] = parts;
      
      if (!nameValue) continue;

      const [name, value] = nameValue.split('=');
      if (!name) continue;

      const cookie: CookieData = {
        name: name.trim(),
        value: value || '',
        domain: urlObj.hostname,
        path: '/',
        httpOnly: false,
        secure: urlObj.protocol === 'https:',
      };

      // 解析属性
      for (const attr of attributes) {
        if (attr.toLowerCase().startsWith('domain=')) {
          cookie.domain = attr.substring(7);
        } else if (attr.toLowerCase().startsWith('path=')) {
          cookie.path = attr.substring(5);
        } else if (attr.toLowerCase().startsWith('expires=')) {
          const expiresDate = new Date(attr.substring(8));
          cookie.expires = expiresDate.getTime();
        } else if (attr.toLowerCase() === 'httponly') {
          cookie.httpOnly = true;
        } else if (attr.toLowerCase() === 'secure') {
          cookie.secure = true;
        }
      }

      cookies.push(cookie);
      this.setCookie(cookie);
    }

    return cookies;
  }

  private matchesDomain(cookieDomain: string, requestDomain: string): boolean {
    if (cookieDomain === requestDomain) return true;
    if (cookieDomain.startsWith('.')) {
      return requestDomain.endsWith(cookieDomain.substring(1)) || 
             requestDomain === cookieDomain.substring(1);
    }
    return false;
  }

  private matchesPath(cookiePath: string, requestPath: string): boolean {
    if (cookiePath === requestPath) return true;
    if (requestPath.startsWith(cookiePath)) {
      return cookiePath.endsWith('/') || 
             requestPath[cookiePath.length] === '/' ||
             requestPath.length === cookiePath.length;
    }
    return false;
  }

  private saveToStorage(): void {
    const cookiesArray = Array.from(this.cookies.entries());
    localStorage.setItem(`tab_cookies_${this.tabId}`, JSON.stringify(cookiesArray));
  }

  private loadFromStorage(): void {
    const stored = localStorage.getItem(`tab_cookies_${this.tabId}`);
    if (stored) {
      try {
        const cookiesArray = JSON.parse(stored) as [string, CookieData][];
        this.cookies = new Map(cookiesArray);
      } catch (error) {
        console.error('加载Cookie失败:', error);
      }
    }
  }
}